import type { App } from 'vue';
import { ElLoading } from 'element-plus';
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading';

/**
 * 自定义下载指令
 * @description 使用方式：v-down="[url,name,isLoading]"，如 `<div v-down="['https://www.baidu.com','ceshi.txt',false]"></div>`
 * @description url 下载文件路径 name 下载文件名称 isLoading 是否显示loading
 */
export default (app: App) => {
	app.directive('down', {
		mounted(el, binding) {
			if (!binding.value[0]) return false;
			el.$value = binding.value;
			el.handler = () => {
				let link = document.createElement('a');
				let url = el.$value[0];
				let fileName = el?.$value[1] ? el.$value[1] : url.substring(url.lastIndexOf('/') + 1);
				let isLoading = el?.$value[2] ? el.$value[2] : false;
				let loadingInstance: LoadingInstance;
				if (isLoading) {
					loadingInstance = ElLoading.service({
						text: '正在下载中...',
						fullscreen: true,
						lock: false,
						body: true,
						background: 'rgba(255, 255, 255, 0.4)',
					});
				}

				// 这里是将url转成blob地址、注意跨域问题
				fetch(url)
					.then((res) => res.blob())
					.then((blob) => {
						if (isLoading) loadingInstance?.close();
						link.style.display = 'none';
						link.href = URL.createObjectURL(blob);
						link.download = fileName;
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
						window.URL.revokeObjectURL(link.href);
					});
			};
			el.addEventListener('click', el.handler);
		},
		updated(el, binding) {
			el.$value = binding.value;
		},
		unmounted(el) {
			el.removeEventListener('click', el.handler);
		},
	});
};
